﻿using System;
using System.Collections;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AMS.Inventory.Entities;
using AMSInventoryWeb.BaseData.Importors;
using VitCode.Castle.Helper;
using VitCode.Web.UI;
using VitCode.Web.UI.ExcelFileGenerator;
using VitCode.Castle.Management;

namespace AMSInventoryWeb.UserControls
{
    public partial class ImportAssetInfoCtl : UserControl
    {
        private BaseDataManager m_Acc = new BaseDataManager();
        public SelectAssetImportor Importor
        {
            get { return (SelectAssetImportor) Session["SelectAssetImportor"]; }
            set { Session["SelectAssetImportor"] = value; }
        }

        private ErrorResult ErrorMessageResult
        {
            get
            {
                if (Session["ErrorMessageResult"] == null)
                {
                    return new ErrorResult();
                }
                return (ErrorResult) Session["ErrorMessageResult"];
            }
            set { Session["ErrorMessageResult"] = value; }
        }

        private DataTable ErrorDataResult
        {
            get
            {
                if (Session["ErrorDataResult"] == null)
                {
                    return new DataTable();
                }
                return (DataTable) Session["ErrorDataResult"];
            }
            set { Session["ErrorDataResult"] = value; }
        }

        public string PlanId
        {
            get { return hdnPlanId.Value; }
            set
            {
                string strVal = value;
                if (strVal == null || strVal.Length != 36)
                    strVal = Guid.Empty.ToString();
                hdnPlanId.Value = strVal;
            }
        }

        public void SetCtlDisabled()
        {
            btnCheckData.Enabled = false;
            btnImport.Enabled = false;
        }

        private object BindErrorMessages()
        {
            return ErrorMessageResult;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Cookies["Code"] == null)
            {
                Response.Redirect("../Default.aspx");
            }
            pgError.DataSourceDelegate = new PaginationGrid.GridDataSourceDelegate(BindErrorMessages);
            btnImport.Attributes.Add("onclick",
                                     "setTimeout('document.all(\"" + btnImport.ClientID + "\").disabled=true;',10);");
            btnCheckData.Attributes.Add("onclick",
                                        "setTimeout('document.all(\"" + btnCheckData.ClientID +
                                        "\").disabled=true;',10);");
            btnOutput.Enabled = (Importor != null);
            if (!IsPostBack)
            {
                Importor = null;
                ErrorMessageResult = null;
                tblBaseInfo.Visible = true;
               
            }
            if (PlanId != null && PlanId.Length == 36)
            {
                var objList = m_Acc.GetObjectList(new PlanInfo().GetType().Name, "Id", PlanId);
                if (objList != null && objList.Count > 0)
                {
                    var currentPlan = (PlanInfo)objList[0];
                    int iMaxAssetAmount = currentPlan.MaxAssetAmount;
                    txtMaxAssetAmount.Text = iMaxAssetAmount.ToString();
                }
            }
          
        }

        protected void btnCheckData_Click(object sender, EventArgs e)
        {
            Importor = null;
            btnImport.Enabled = false;
            DateTime S_datetime = DateTime.Now;
            lblMessage.Text = "";
            if (fileSource.Value == "")
            {
                lblCheckSource.Text = "请选择导入文件";
                return;
            }

            string strFileName = fileSource.PostedFile.FileName;
            int index = strFileName.LastIndexOf("\\");
            strFileName = strFileName.Substring(index + 1, strFileName.Length - index - 1);

            if (strFileName.Substring(strFileName.Length - 4).ToLower() != ".xls")
            {
                lblMessage.Text = "请使用正确的模板文件";
                pgError.Visible = false;
                return;
            }

            string path = Path.GetTempPath() + DateTime.Now.Ticks.ToString().Substring(5) + strFileName;
            fileSource.PostedFile.SaveAs(path);

            try
            {
                Importor = new SelectAssetImportor(path, txtSheetName.Text, PlanId);
                Importor.Check();
                DataTable dt = Importor.GetSourceData(true);
                int sourceDataCount = dt.Rows.Count;
                int errorDataCount = 0;
                if (Importor.ErrorMessage.Rows.Count == 0)
                {
                    pgError.Visible = false;
                    ErrorDataResult = null;
                    ErrorMessageResult = null;
                }
                else
                {
                    pgError.Visible = true;
                    pgError.SortExpression = "行号";
                    ErrorMessageResult = Importor.ErrorMessage;
                    pgError.BindGrid();
                    ErrorDataResult = Importor.GetSourceData(false);
                    errorDataCount = ErrorDataResult.Rows.Count;
                }

                DateTime F_Datetime = DateTime.Now;
                TimeSpan showtime = F_Datetime - S_datetime;
                lblMessage.Text = "正确数据： " + sourceDataCount + " 条，错误数据： " + errorDataCount + " 条，校验所耗时间：" +
                                  showtime.Hours + " 时 " +
                                  showtime.Minutes + " 分 " + showtime.Seconds + " 秒";
                btnImport.Enabled = sourceDataCount > 0;
            }
            catch (ArgumentNullException ex)
            {
                Alert.WebMessageBox(Page,ex.Message);
            }
            catch (ArgumentOutOfRangeException ex2)
            {
                Alert.WebMessageBox(Page,ex2.Message);
            }
            catch (ArgumentException ex3)
            {
                Alert.WebMessageBox(Page,ex3.Message);
            }
            catch (OleDbException ex4)
            {
                if (ex4.ErrorCode == -2147467259)
                    Alert.WebMessageBox(Page,"在上传附件中找不到表名为 “" + txtSheetName.Text + "” 的工作表");
            }
            btnOutput.Enabled = Importor != null;
        }

        public virtual void InvokeObjMethod(string methodName, object obj, Parameter[] ps)
        {
            if (obj == null || obj.GetType() == null)
                return;
            MethodInfo mi = obj.GetType().GetMethod(methodName);
            if (mi != null)
                mi.Invoke(obj, ps);
        }

        protected void btnImport_Click(object sender, EventArgs e)
        {
            DateTime S_datetime = DateTime.Now;
            lblMessage.Text = "";
            StringBuilder sbErrInfo = new StringBuilder();
            txtMaxAssetAmount.BackColor = Color.Transparent;
            if (txtMaxAssetAmount.Text.Length == 0)
            {
                sbErrInfo.Append("【单计划最大资产量】不能为空\r\n");
                txtMaxAssetAmount.BackColor = Color.Yellow;
            }
            else
            {
                Regex reg = new Regex("\\d+$");
                if (!reg.IsMatch(txtMaxAssetAmount.Text))
                {
                    sbErrInfo.Append("【单计划最大资产量】必需是大于0的整数\r\n");
                    txtMaxAssetAmount.BackColor = Color.Yellow;
                }
            }

            int maxAssetAmount = Convert.ToInt32(txtMaxAssetAmount.Text);

            if (sbErrInfo.Length > 0)
            {
                Alert.MessageBox(sbErrInfo.ToString());
                return;
            }

            try
            {
                Importor.Import(Importor.GetSourceData(true), false);
                Importor.MaxAssetAmount = maxAssetAmount;
                

                pgError.Visible = false;
                ErrorDataResult = null;
                ErrorMessageResult = null;

                object objCtl = Page.FindControl("ctlSelected");
                InvokeObjMethod("SetData", objCtl, null);
                if (Importor.SaveErrMsg != null && Importor.SaveErrMsg.Length > 0)
                    Alert.MessageBox(Importor.SaveErrMsg.ToString());
                else
                {
                    DateTime F_Datetime = DateTime.Now;
                    TimeSpan showtime = F_Datetime - S_datetime;
                    lblMessage.Text = "导入更新数据： "  + Importor.UpdateCount
                                      + " 条，导入所耗时间：" + showtime.Hours + " 时 " + showtime.Minutes + " 分 " + showtime.Seconds +
                                      " 秒";
                }
                
            }
            catch (ArgumentNullException ex)
            {
                Alert.WebMessageBox(Page,ex.Message);
            }
            catch (ArgumentOutOfRangeException ex2)
            {
                Alert.WebMessageBox(Page,ex2.Message);
            }
            catch (ArgumentException ex3)
            {
                Alert.WebMessageBox(Page,ex3.Message);
            }
            catch (SqlException sqlex)
            {
                if (sqlex.Message.IndexOf("违反了 UNIQUE KEY 约束") > -1)
                {
                    Alert.WebMessageBox(Page,"系统中同时插入相同的条码，请再一次进行机校验数据");
                }
            }
            catch (OleDbException ex4)
            {
                if (ex4.ErrorCode == -2147467259)
                    Alert.WebMessageBox(Page,"在上传附件中找不到表名为 “" + txtSheetName.Text + "” 的工作表");
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                Importor = null;
                btnImport.Enabled = false;
            }
        }

        protected void btnOutput_Click(object sender, EventArgs e)
        {
            int errorMsgColIndex = 1, errorRowNumColIndex = 0;
            if (Importor == null)
                return;
            DataTable result = null;
            DataTable source = Importor.SourceData;
            var tmpHt = new Hashtable();
            if (source == null || source.Rows.Count == 0)
            {
                Alert.WebMessageBox(Page,"模板中没有数据");
                return;
            }
            for (int i = 0; i < ErrorMessageResult.Rows.Count; i++)
            {
                DataRow r = ErrorMessageResult.Rows[i];
                tmpHt.Add(r[errorRowNumColIndex], r[errorMsgColIndex]);
            }
            for (int i = 0; i < source.Rows.Count; i++)
            {
                if (i == 0)
                {
                    result = ErrorDataResult.Clone();
                    result.Columns.Add("检验结果");
                    result.Columns.Add("出错信息");
                }
                var objs = new object[result.Columns.Count];
                source.Rows[i].ItemArray.CopyTo(objs, 0);
                string[] tempObjs;
                if (tmpHt.ContainsKey(i + 2))
                    tempObjs = new[] {"错误", tmpHt[i + 2].ToString()};
                else
                    tempObjs = new[] {"正确"};
                tempObjs.CopyTo(objs, source.Columns.Count);
                DataRow r = result.NewRow();
                r.ItemArray = objs;
                result.Rows.Add(r);
            }
            var exporter = new ExcelFileGenerator();
            string tempPath = exporter.ExportDataToExcelFile(result);
            Response.Charset = "GB2312";
            Response.AppendHeader("Content-Disposition",
                                  "attachment;filename=" +
                                  HttpUtility.UrlEncode("导入模板输出(带校验信息)_" + DateTime.Now.ToString("yyyyMMdd") + ".xls"));
            Response.ContentEncoding = Encoding.Default;
            Response.ContentType = "application/ms-excel";
            Response.Clear();
            Response.WriteFile(tempPath);
            Response.End();
        }

        protected void lbGetImportorFile_Click(object sender, EventArgs e)
        {
            Response.Redirect("ImportorFiles/CN/" + Server.UrlEncode(lbGetImportorFile.Text + ".zip"));
        }
    }
}